/******** printf debug *******


****** Create  by sam.zhou**************

*************************************/

#include "printf.h"
#include "hal_uart.h"
#include <stdarg.h>

void UartSendByte(uint8 data, uint8 which)
{
        uint8 buf[1];
        buf[0] = data;
	if(data == '\n')
	{
                uint8 temp[1];
                temp[0] = '\r';
		HalUARTWrite(which,temp,1);
	}
	HalUARTWrite(which, buf, 1);
}

void UartSendStr(const char *pstr,uint8 which)
{
	if(pstr == NULL)
	{
		return ;
	}
	
	while(*(pstr)!='\0')
	{
		UartSendByte(*(pstr++),which);
	}
}

static char * fh_itoa(int data,char *pstr,int radio)
{
	int tag=0;
	if(radio == 10)
	{

		while(1)
		{

			*(pstr+tag)=(data%10)+'0';
			tag++;
			data=data/10;
			if(data == 0)
			{
				break;
			}
		}
	}
	else if(radio==16)
	{
		IntStrHex( data,pstr);
	}

	return pstr;
}

 static void IntStrHex(int data,char *pstr)
{
	uint8 ret;
	int   i;
	int tag=0;
	for(i=7;i>=0;i--)
	{
		ret=(data>>4*i)&0xf;
		if(ret>9)
		{
			ret=(ret-10)+'A';
		}
		else
		{
			ret='0'+ret;
		}
		//Uart_SendByte(ret);
		*(pstr+tag)=ret;
		tag++;
	}

}

static void reverse_str(char *pstr)
{
	if(pstr == 0)
	{
		return;
	}

	int len=0;int i=0;
	while(*(pstr+i)!='\0')
	{
		len++;
		i++;
	}

	char temp='\0';
	for(i=0;i<len/2;i++)
	{
		temp=pstr[i];
		pstr[i]=pstr[len-i-1];
		pstr[len-i-1]=temp;

	}

}

int uprintf(char *format,...)
{
	
	va_list ap=0;
	va_start(ap,format);

	while(*format!='\0')
	{
		if(*format == '%')
		{
			switch(*(format+1))
			{
				case 'c':
				{
					char temp='\0';
					
					temp=va_arg(ap,char);
					UartSendByte(temp,UART0_SELECT);
					
					break;
				}
				case 'd':
				{
					int temp=0;
					char buf[32]={'\0'};
					temp=va_arg(ap,int);
					fh_itoa(temp,buf,10);
					reverse_str(buf);
					 UartSendStr(buf,UART0_SELECT);
					break;
				}
				case 'x':
				case 'X':
				{
					int temp=0;
					char buf[32]={'\0'};
					temp=va_arg(ap,int);
					fh_itoa(temp,buf,16);
					//reverse_str(buf);
					UartSendStr("0x",UART0_SELECT);
					 UartSendStr(buf,UART0_SELECT);
					break;
				}
				case 's':
				{
					int temp=0;
					//int i=0;
					temp=va_arg(ap,int);
					//temp=*(int *)ap;
					/*while(*(temp+i))
					{
						Uart_SendByte(*(temp+i));
						i++;
					}*/
					char *parg_addr=0;
					parg_addr=(char *)temp;
					int i=0;

					while(*(parg_addr+i)!='\0')
					{
						UartSendByte(*(parg_addr+i),UART0_SELECT);
						i++;
					}

					break;
				}
				default:
				{

					UartSendByte(*(format+1),UART0_SELECT);
					//format=format+2*sizeof(char);
					break;
				}
			}
			format=format+2*sizeof(char);
		}
		else
		{
			UartSendByte(*format,UART0_SELECT);
			format++;
		}




		//format++;
	}
	return 0;
}
